﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Windows.Forms;

namespace Stote.Forms
{
    public partial class FrmOutboundRecordAddAndEdit : BaseForm
    {
        Form parentForm = null;
        Dong.BLL.OutboundRecord OutboundRecordBLL = new Dong.BLL.OutboundRecord();
        Dong.BLL.StorageRecord storageRecordBLL = new Dong.BLL.StorageRecord();
        Dong.BLL.StoreArea storeAreaBLL = new Dong.BLL.StoreArea();
        Dong.BLL.Product productBLL = new Dong.BLL.Product();
        Dong.BLL.Inventory inventoryBLL = new Dong.BLL.Inventory();
        Dong.Model.OutboundRecord editModel = null;
        int editId = 0;
        public FrmOutboundRecordAddAndEdit()
        {
            InitializeComponent();
        }
        public FrmOutboundRecordAddAndEdit(int id, Form parent)
        {
            InitializeComponent();
            parentForm = parent;
            Bind();

            btnAdd.Click += BtnAdd_Click;
            btnStoreArea.Click += BtnStoreArea_Click;
            btnProduct.Click += BtnProduct_Click;
            dtpOutboundTime.ValueChanged += DtpOutboundTime_ValueChanged;

            if (id == 0)
            {
                editId = 0;
                editModel = null;
                WinText = "添加";
                btnAdd.Text = "添加";
                btnAdd.Image = Properties.Resources.add;
                btnStoreArea.Visible = true;
                btnProduct.Visible = true;

                dtpOutboundTime.Format = DateTimePickerFormat.Custom;
                dtpOutboundTime.CustomFormat = " ";
            }
            else
            {
                editId = id;
                editModel = OutboundRecordBLL.GetModel(editId);
                WinText = "编辑";
                btnAdd.Text = "保存";
                btnAdd.Image = Properties.Resources.save;
                btnStoreArea.Visible = false;
                btnProduct.Visible = false;

                dtpOutboundTime.Format = DateTimePickerFormat.Custom;
                dtpOutboundTime.CustomFormat = "yyyy-MM-dd HH:mm";

                cbStoreArea.SelectedValue = Convert.ToInt32(editModel.StoreAreaId);
                cbProduct.SelectedValue = Convert.ToInt32(editModel.ProductId);
                txtAmount.Text = editModel.Amount.ToString();
                dtpOutboundTime.Value = editModel.OutboundTime;
                rtbRemark.Text = editModel.Remark;
            }
        }

        private void DtpOutboundTime_ValueChanged(object sender, EventArgs e)
        {
            dtpOutboundTime.Format = DateTimePickerFormat.Custom;
            dtpOutboundTime.CustomFormat = "yyyy-MM-dd HH:mm";
        }

        private void BtnProduct_Click(object sender, EventArgs e)
        {
            FrmMain mainForm = parentForm.ParentForm as FrmMain;
            mainForm.ToggleSelected("产品管理");
            mainForm.OpenForm(new FrmProduct(), "产品管理");
            this.Close();
        }

        private void BtnStoreArea_Click(object sender, EventArgs e)
        {
            FrmMain mainForm = parentForm.ParentForm as FrmMain;
            mainForm.ToggleSelected("分区管理");
            mainForm.OpenForm(new FrmArea(), "分区管理");
            this.Close();
        }

        private void Bind()
        {
            DataSet ds = storeAreaBLL.GetList(" Status=0");
            DataTable dt = ds.Tables[0];
            DataRow dr = dt.NewRow();
            dr["StoreAreaId"] = -1;
            dr["StoreAreaName"] = "全部";
            dt.Rows.InsertAt(dr, 0);
            cbStoreArea.DataSource = dt;
            cbStoreArea.DisplayMember = "StoreAreaName";
            cbStoreArea.ValueMember = "StoreAreaId";

            DataSet ds2 = productBLL.GetList(" Status=0");
            DataTable dt2 = ds2.Tables[0];
            DataRow dr2 = dt2.NewRow();
            dr2["ProductId"] = -1;
            dr2["ProductName"] = "全部";
            dt2.Rows.InsertAt(dr2, 0);
            cbProduct.DataSource = dt2;
            cbProduct.DisplayMember = "ProductName";
            cbProduct.ValueMember = "ProductId";
        }

        private void BtnAdd_Click(object sender, EventArgs e)
        {
            try
            {
                if (Convert.ToInt32(cbStoreArea.SelectedValue) == -1)
                {
                    MessageBox.Show("请选择出库区域！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                if (Convert.ToInt32(cbProduct.SelectedValue) == -1)
                {
                    MessageBox.Show("请选择出库产品！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                if (string.IsNullOrEmpty(txtAmount.Text.Trim()))
                {
                    MessageBox.Show("请输入产品数量！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                if (string.IsNullOrEmpty(dtpOutboundTime.Text.Trim()))
                {
                    MessageBox.Show("请选择出库日期！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                int storeAreaId = Convert.ToInt32(cbStoreArea.SelectedValue);
                int productId = Convert.ToInt32(cbProduct.SelectedValue);
                int amount = Convert.ToInt32(txtAmount.Text.Trim());

                if (amount <= 0)
                {
                    MessageBox.Show("出库的产品数量不能小于等于0！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                // 判断出库产品数量是否够
                List<Dong.Model.Inventory> list = inventoryBLL.GetModelList($" Status=0 AND ProductId={productId} AND StoreAreaId={storeAreaId}");
                int totalAmount = 0;
                foreach (var item in list) totalAmount += (int)item.Amount;
                if (amount > totalAmount)
                {
                    MessageBox.Show("出库的产品数量不能大于此区域的库存量！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                if (editId == 0)
                {
                    Dong.Model.OutboundRecord model = new Dong.Model.OutboundRecord()
                    {
                        StoreAreaId = storeAreaId,
                        ProductId = productId,
                        Amount = amount,
                        OutboundTime = dtpOutboundTime.Value,
                        Remark = rtbRemark.Text.Trim(),
                        CreateUserId = FrmLogin.CurrentUser.UserId,
                    };

                    OutboundRecordBLL.Add(model);

                    UpdateInventory(storeAreaId, productId, amount);
                }
                else
                {
                    // 保存原区域，原产品的信息，目的，修改数据时，把原区域，原产品的数量增加库存，新区域，新产品的数量减少库存
                    int oldStoreAreaId = editModel.StoreAreaId;
                    int oldProductId = editModel.ProductId;
                    int oldAmount = editModel.Amount;

                    // 编辑库存记录。OutboundRecord表
                    editModel.StoreAreaId = storeAreaId;
                    editModel.ProductId = productId;
                    editModel.Amount = amount;
                    editModel.OutboundTime = dtpOutboundTime.Value;
                    editModel.Remark = rtbRemark.Text.Trim();
                    editModel.LastUpdateUserId = FrmLogin.CurrentUser.UserId;
                    editModel.LastUpdateTime = DateTime.Now;
                    OutboundRecordBLL.Update(editModel);

                    UpdateInventory(storeAreaId, productId, amount);// 减少
                    UpdateInventory(oldStoreAreaId, oldProductId, -oldAmount);  // 增加
                }

                DialogResult = DialogResult.OK;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
        }

        private void UpdateInventory(int storeAreaId, int productId, int amount)
        {
            // 查询库存盘点表中是否已经存在某个区域的某个产品，如果存在，则更新产品数量
            // 对于出库单来说，库存中肯定存在，不存在库存，业务逻辑就进入不了此处。
            DataSet ds = inventoryBLL.GetList($" Status=0 AND ProductId={productId} AND StoreAreaId={storeAreaId}");
            if (ds.Tables[0].Rows.Count > 0)
            {
                // 更新库存盘点表中的产品数量
                int inventoryId = Convert.ToInt32(ds.Tables[0].Rows[0]["InventoryId"]);
                Dong.Model.Inventory inventoryModel = inventoryBLL.GetModel(inventoryId);
                inventoryModel.Amount -= amount;
                inventoryModel.LastUpdateUserId = FrmLogin.CurrentUser.UserId;
                inventoryModel.LastUpdateTime = DateTime.Now;
                inventoryBLL.Update(inventoryModel);
            }
        }
    }
}
